package com.greensam.pixelengine.api.imagesearch.sub;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.greensam.pixelengine.exception.BusinessException;
import com.greensam.pixelengine.exception.ThrowUtils;
import com.greensam.pixelengine.pojo.emuns.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 获取以图搜图页面地址
 *
 * @author Ma Chengrui
 * @since 2025/9/16 16:26
 */
@Slf4j
public class GetImagePageUrlApi {

    /**
     * @param imageUrl 图片地址
     * @author Ma Chengrui
     * @since 2025/9/16
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1. 准备请求参数
        HashMap<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        formData.put("sdkParams","");
        // 请求地址
        long uptime = System.currentTimeMillis();
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;

        try {
            // 2. 发送请求
            HttpResponse httpResponse = HttpRequest.post(url)
                    .header("acs-token", RandomUtil.randomString(10))
                    .form(formData)
                    .timeout(5000)
                    .execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                throw new BusinessException(ErrorCodeEnum.OperationDataError, "接口调用失败");
            }

            // 解析响应
            // {"status":0,"msg":"Success","data":{"url":"https://graph.baidu.com/s","sign":"126d80fe67ef5eb7d07ae01758012278"}}
            String body = httpResponse.body();
            Map<String, Object> result = JSONUtil.toBean(body, Map.class);

            // 3. 处理响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCodeEnum.OperationDataError, "接口调用失败");
            }

            Object dataObj = result.get("data");
            if (dataObj == null || dataObj instanceof cn.hutool.json.JSONNull) {
                throw new BusinessException(ErrorCodeEnum.OperationDataError, "接口返回数据为空");
            }
            if (!(dataObj instanceof Map)) {
                throw new BusinessException(ErrorCodeEnum.OperationDataError, "接口返回数据格式错误");
            }
            Map<String, Object> data = (Map<String, Object>) dataObj;

            // 对 URL 进行解码
            String rawUrl = (String) data.get("url");
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            ThrowUtils.throwIf(StringUtils.isBlank(searchResultUrl), ErrorCodeEnum.DataNotExist, "未返回有效的结果地址");
            return searchResultUrl;
        } catch (Exception e) {
            log.error("获取图片搜索结果页地址失败", e);
            throw new BusinessException(ErrorCodeEnum.OperationDataError, "接口调用失败");
        }
    }

    public static void main(String[] args) {
        // 测试以图搜图
        String imageUrl = "https://picture-1317641405.cos.ap-guangzhou.myqcloud.com/Greensam/private/1/2025-09-16_2J2sR69puXQm.jpg";
        String imagePageUrl = getImagePageUrl(imageUrl);
        System.out.println("以图搜图的测试结果：" + imagePageUrl);
    }
}
